package com.wj.onlinemusic.controller;
import com.wj.onlinemusic.mapper.UserMapper;
import com.wj.onlinemusic.model.User;
import com.wj.onlinemusic.tools.Constant;
import com.wj.onlinemusic.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(@RequestParam String username, @RequestParam String password,
                                           HttpServletRequest request) {
        User user = userMapper.selectByName(username);
        if(user == null) {
            System.out.println("登录失败！");
            return new ResponseBodyMessage<>(-1,"用户名或者密码错误！",user);
        }else {
            boolean flg = bCryptPasswordEncoder.matches(password,user.getPassword());
            if(!flg) {
                return new ResponseBodyMessage<>(-1,"用户名或者密码错误！",user);
            }
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponseBodyMessage<>(0,"登录成功！",user);
        }
    }
}